package com.example.localgateway;

import com.example.environmentset.service.PortSetService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Objects;

@SpringBootApplication
@Slf4j
public class LocalGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(LocalGatewayApplication.class, args);
    }

    @Autowired
    private PortSetService portSetService;

    @SneakyThrows
    @Bean
    public RouteLocator routes(RouteLocatorBuilder builder) {
        RouteLocatorBuilder.Builder routeBuilder = builder.routes();
        String targetHostProp = System.getProperty("target.host");
        log.info("routes targetHostProp={}", targetHostProp);
        String targetHostEnv = System.getenv("target.host");
        log.info("routes targetHostEnv={}", targetHostEnv);

        if (!StringUtils.hasText(targetHostProp) && !StringUtils.hasText(targetHostEnv)) {
            log.info("routes target.host is null");
            return routeBuilder.build();
        }
        String property = StringUtils.hasText(targetHostProp) ? targetHostProp : targetHostEnv;

        // 根据应用和启动端口动态构建router
        for (Map.Entry<String, Integer> contextAndPort : portSetService.get().entrySet()) {
            log.info("routes contextAndPort={},{}", contextAndPort.getKey(), contextAndPort.getValue());
            routeBuilder
                    .route(predicateSpec -> predicateSpec.predicate(serverWebExchange -> {
                                // /a/b/c 0->/ 1->a ... 5->c
                                String context = serverWebExchange.getRequest().getPath().subPath(1, 2).toString();
                                return Objects.equals(context, contextAndPort.getKey());
                            })
                            .uri("http://" + property + ":" + contextAndPort.getValue()));
        }
        return routeBuilder.build();

    }
}
